package com.tianci.appstore.point;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.framework.utils.LogUtils;
import com.skyworth.framework.skysdk.util.SkyJSONUtil;
import com.skyworth.framework.skysdk.util.SkyObjectByteSerialzie;
import com.tianci.user.api.bonuspoint.BonusPointAddResult;
import com.tianci.user.api.bonuspoint.BonusPointHttpResult;
import com.tianci.user.data.UserCmdDefine;

public class  PointResultReceiver extends BroadcastReceiver {
    private final String FAIL_MAX_TIMES = "ERROR_TRIGGER_MAX_TIMES";
    private final String TRIGGER_TYPE = "ONCE";

    @Override
    public void onReceive(Context arg0, final Intent intent)
    {
        String action = intent.getAction();
        LogUtils.d("PointResult", "sunny point add onReceive = " + action);
        if (UserCmdDefine.ACTION_BONUS_POINT_ADD_RESULT.equals(action)) {
            byte[] byteArray = intent.getByteArrayExtra(UserCmdDefine.KEY_BONUS_POINT_DATA);
            if (byteArray != null && byteArray.length > 0) {
                BonusPointAddResult addRes = SkyObjectByteSerialzie.toObject(byteArray,
                        BonusPointAddResult.class);
                if (addRes != null && addRes.itemInfo != null && addRes.itemInfo.itemTag != null && addRes.itemInfo.triggerType!= null
                        && (isNeedSave(addRes.itemInfo.itemTag) ||addRes.itemInfo.triggerType.equals(TRIGGER_TYPE))) {
                    // 根据itemInfo中的itemTag来判断是哪个积分行为的结果。
                    LiteAppApplication.setFirstLaunch(addRes.itemInfo.itemTag);
                }
            }
        } else if (UserCmdDefine.ACTION_BONUS_POINT_ADD_FAILED.equals(action)) {
            String json = intent.getStringExtra(UserCmdDefine.KEY_BONUS_POINT_DATA);
            BonusPointHttpResult result = SkyJSONUtil.getInstance().parseObject(json,
                    BonusPointHttpResult.class);
            if(result != null && result.code != null && result.code.equals(FAIL_MAX_TIMES)
                    && result.itemTag!= null && !result.itemTag.equals("") && isNeedSave(result.itemTag)){
                LiteAppApplication.setFirstLaunch(result.itemTag);
            }
        }
    }

    private boolean isNeedSave(String tag){
        if(tag != null && (tag.equals("FIRST_TVPAI")||tag.equals("FIRST_APP_OPEN")||tag.equals("FIRST_KYB_OPEN"))){
            return true;
        }
        return false;
    }
}
